package com.engine.common.util.CacheUtil;

import com.engine.init.Globle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 * @author  sunzx
 */
@Component
@Slf4j
public class BufferRedisUtil {

    @Resource(name = "redisLocalTemplate")
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 读取缓存
     * @param key
     * @return
     */
    public String get(final String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public Boolean set(final String key,String value){
        Boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            return result = true;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return result;
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @param outTime
     * @return
     */
    public Boolean set(final String key, String value, long outTime, TimeUnit timeUnit){
        Boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value,outTime,timeUnit);
            return result = true;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return result;
    }

    /**
     * 删除缓存
     * @param key
     * @return
     */
    public Boolean del(final String key){
        Boolean result = false;
        try {
            redisTemplate.delete(key);
            return  result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public Object getBuffer(String key) {
        if(Globle.vectorBuffer==0)
            return null;
        return redisTemplate.opsForValue().get(key);
    }

    public void setBuffer(String key,byte[] b) {
        if(Globle.vectorBuffer==1)
            redisTemplate.opsForValue().set(key,b.toString());
    }
}
